package com.scale.service.voice.controller;

import com.example.common.result.Result;
import com.example.voice.dto.CreateVoiceTaskDTO;
import com.example.voice.vo.VoiceTaskVO;
import com.scale.service.voice.service.VoiceTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 语音任务管理控制器
 * @author crp
 * @since 2025-01-26
 */
@Api(tags = "语音流式处理")
@RestController
@RequestMapping("/api/voice")
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:3001", "http://localhost:5173", "http://localhost:8081"}, 
             methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS}, 
             allowedHeaders = "*", allowCredentials = "true")
public class VoiceTaskController {
    
    @Autowired
    private VoiceTaskService voiceTaskService;
    
    /**
     * 创建语音处理任务
     */
    @ApiOperation("创建语音处理任务")
    @PostMapping("/stream-task")
    public Result<VoiceTaskVO> createStreamTask(
            @ApiParam("创建语音任务请求") @RequestBody @Validated CreateVoiceTaskDTO dto) {
        
        try {
            VoiceTaskVO result = voiceTaskService.createTask(dto);
            return Result.success("任务创建成功", result);
        } catch (Exception e) {
            return Result.error("任务创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询任务状态
     */
    @ApiOperation("查询任务状态")
    @GetMapping("/task-status/{taskId}")
    public Result<VoiceTaskVO> getTaskStatus(
            @ApiParam("任务ID") @PathVariable String taskId) {
        
        try {
            VoiceTaskVO result = voiceTaskService.getTaskStatus(taskId);
            if (result != null) {
                return Result.success("查询成功", result);
            } else {
                return Result.error("任务不存在");
            }
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消任务
     */
    @ApiOperation("取消任务")
    @DeleteMapping("/task/{taskId}")
    public Result<String> cancelTask(
            @ApiParam("任务ID") @PathVariable String taskId) {
        
        try {
            boolean success = voiceTaskService.cancelTask(taskId);
            if (success) {
                return Result.success("任务已取消");
            } else {
                return Result.error("任务取消失败或任务不存在");
            }
        } catch (Exception e) {
            return Result.error("取消失败: " + e.getMessage());
        }
    }
}
